from django.shortcuts import render

import datetime

from django.http import HttpResponse

from django.db.models import F

from core import film_core

from .models import *

FilmSearch = film_core.FilmSearch


# Create your views here.





def index(request):

    context = {}

    #return render(request, 'index.html', context)



    return render(request, 'film_app2/index.html', context)
    return render(request, 'film_app/sousuokuang.html', context)

def search(request):

    if request.method == 'POST':#如果提交方式是POST

        keyword = request.POST.get('keyword')#获取搜索的关键字

        #print(keyword)

        try:

            keyword_count = KeywordCount.objects.get(
                time = datetime.datetime.now().date(), 
                keyword = keyword)

        except KeywordCount.DoesNotExist:

            KeywordCount.objects.create(time = datetime.datetime.now().date(), keyword = keyword, count = 1)

        else:

            #keyword_count.count += 1  #多个用户同时访问时会出现记数不准确的bug,要使用用F()函数

            keyword_count.count = F('count') + 1
            keyword_count.save()

            #keyword_count.objects.update(count = F('count') + 1)


        search_info = FilmSearch().get_search_info(keyword)
    
        context = {'search_list':search_info, 'keyword': keyword}

        return render(request, 'film_app2/search-list.html', context)
        return render(request, 'film_app/list.html', context)


    else:##如果提交方式是GET

        context = {}

        return render(request, 'film_app/sousuokuang.html', context)


def www123ku(request):

    value = request.GET.get('m')#m表示要播放的电影名称

    num = request.GET.get('num')#num 表示要播放哪一集视频

    if value == None:

        context = {}

        return render(request, 'film_app/index1.html', context)

    else:
        url = 'http://www.123ku.com/?m={}'.format(value)

        info = FilmSearch().get_film_info(url)

        url_list = info['show_url']#获取数据

        film_name = info['name']

        ###########数据清理#############

        #joint_url = '/app/123ku/?m=vod-detail-id-13518.html&num={}'

        url_m3u8 = []##把以m3u8结尾的视频链接提出来

        for i in url_list:

            if i[0].endswith('m3u8'):

                url_m3u8.append(i)

        if num == None:#表示无num参数时，默认播放第一集

            num = 0


        url_show = []#播放链接

        joint_url = '/app/123ku/?m={}&num={}'

        for i in range(len(url_m3u8)):#生成渲染时需要的链接

            show = (joint_url.format(value, i), url_m3u8[i][1])

            url_show.append(show)

        #print(url_show)

        context = {'url_list': url_show, 'show':url_m3u8[int(num)], 'film_name':film_name,'jie_shao':info['jie_shao']}

        return render(request, 'film_app2/play.html', context)
        return render(request, 'film_app/single1.html', context)
            



    








